<template>
  <div class="home">
    <FilterBar
      :searchQuery="searchQuery"
      :selectedTags="selectedTags"
      :sortBy="sortBy"
      :tags="allTags"
      showSearch
      showTags
      showSort
      @update:searchQuery="searchQuery = $event"
      @update:selectedTags="selectedTags = $event"
      @update:sortBy="sortBy = $event"
    />

    <LoadingWrapper :loading="loading">
      <el-row v-if="bookList.length > 0" :gutter="30">
        <el-col :span="6" v-for="book in paginatedBooks" :key="book.id" class="book-col">
          <el-card class="book-card" @click="handleCardClick(book)">
            <div class="book-cover">
              <el-image
                :src="book.images?.[0] || '默认图片URL'"
                fit="cover"
                class="book-image"
              >
                <template #placeholder>
                  <div class="image-placeholder">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
                <template #error>
                  <div class="image-placeholder">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </div>
            <div class="book-info">
              <h3 class="book-title">{{ book.title }}</h3>
              <div class="book-author">作者：{{ book.author }}</div>
              <div class="book-sharer">分享者：{{ book.nickname }}</div>
              <p class="book-description">{{ book.thoughts }}</p>
              <div class="book-meta">
                <div class="tags">
                  <el-tag v-for="tag in book.tags" :key="tag" size="small">{{ tag }}</el-tag>
                </div>
                <div class="stats">
                  <div class="like-count">
                    {{ book.likeCount }}人点赞
                  </div>
                  <div class="rating">
                    <span class="rating-label">综合评分:</span>
                    <span class="rating-value" :class="{ 'no-rating': !book.rating }">
                      {{ book.rating ? `${book.rating}分` : '暂无评分' }}
                    </span>
                  </div>
                </div>
              </div>
              <div class="card-footer">
                <el-button type="text">查看详情</el-button>
                <span class="create-time">
                  分享时间：{{ book.createTime }}
                </span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <el-empty v-else description="暂无数据" />
    </LoadingWrapper>

    <!-- 分页组件 -->
    <PaginationBar
      v-if="filteredBooks.length > 0"
      v-model:currentPage="currentPage"
      v-model:pageSize="pageSize"
      :total="filteredBooks.length"
      :pageSizes="[4, 8, 12, 16]"
      @pagination-change="handlePaginationChange"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted, computed } from 'vue'
import { Picture } from '@element-plus/icons-vue'
import { getBookList } from '@/api/book'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { wsClient } from '@/utils/websocket'
import { useUserStore } from '@/stores/user'
import FilterBar from '@/components/filter/FilterBar.vue'
import PaginationBar from '@/components/pagination/PaginationBar.vue'
import LoadingWrapper from '@/components/loading/LoadingWrapper.vue'

// 基础数据
const searchQuery = ref('')
const selectedTags = ref([])
const sortBy = ref('newest')
const allTags = ref([])
const bookList = ref([])
const currentPage = ref(1)
const pageSize = ref(4)
const router = useRouter()

// 添加 loading 状态
const loading = ref(true)

// 获取书籍列表
const getBooks = async () => {
  try {
    loading.value = true
    const response = await getBookList()
    if (response.code === 200) {
      // 只显示已上架的书籍
      bookList.value = response.data.filter(book => book.status === 1).map(post => ({
        id: parseInt(post.id),
        title: post.title,
        author: post.author,
        nickname: post.nickname,
        thoughts: post.thoughts,
        tags: post.tags ? post.tags.split(/\s+/).filter(tag => tag) : [],  // 将tags字符串转换为数组, 并去除空字符串
        likeCount: post.like_count,
        rating: post.rating ? Math.round(post.rating) : null,
        createTime: new Date(post.created_at).toLocaleDateString(),
        images: post.images ? (
          typeof post.images === 'string' ? 
            JSON.parse(post.images) : 
            post.images
        ) : [],
        status: parseInt(post.status)
      }))
      // 提取所有标签
      const tagSet = new Set()
      bookList.value.forEach(book => {
        book.tags.forEach(tag => tagSet.add(tag))
      })
      allTags.value = Array.from(tagSet)
    }
  } catch (error) {
    console.error('获取书籍列表失败:', error)
    ElMessage.error('获取书籍列表失败')
  } finally {
    loading.value = false
  }
}

// 使用计算属性过滤和排序书籍列表
const filteredBooks = computed(() => {
  // 过滤书籍条件
  const filtered = bookList.value.filter(book => {
    const matchQuery = !searchQuery.value || 
      book.title.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      book.author.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      book.thoughts.toLowerCase().includes(searchQuery.value.toLowerCase())
    
    const matchTag = selectedTags.value.length === 0 || 
      book.tags.some(tag => selectedTags.value.includes(tag))
    
    return matchQuery && matchTag
  })
  
  // 排序书籍
  return filtered.sort((a, b) => {
    switch (sortBy.value) {
      case 'newest':
        return new Date(b.createTime) - new Date(a.createTime)
      case 'mostLiked':
        return b.likeCount - a.likeCount
      case 'highestRated':
        // 处理无评分的情况
        const ratingA = a.rating || 0
        const ratingB = b.rating || 0
        return ratingB - ratingA
      default:
        return 0
    }
  })
})

// 分页后的书籍列表
const paginatedBooks = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredBooks.value.slice(start, end)
})

// 处理分页变化
const handlePaginationChange = ({ type, value }) => {
  if (type === 'page') {
    currentPage.value = value
  } else if (type === 'size') {
    pageSize.value = value
    currentPage.value = 1  // 重置到第一页
  }
}

// 监听筛选条件变化，重置页码
watch([searchQuery, selectedTags, sortBy], () => {
  currentPage.value = 1
})

// 点击卡片跳转到详情页
const handleCardClick = (book) => {
  const userStore = useUserStore()
  
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请登录后重试')
    return
  }

  const routeData = router.resolve({
    path: `/books/${book.id}`
  })
  window.open(routeData.href, `详情-${book.title}`)
}

// 处理书籍状态变化
const handleBookStatusChange = ({ bookId, status, isDelete }) => {
  const book = bookList.value.find(b => b.id === parseInt(bookId))
  if (book) {
    if (status === 0) {
      // 下架或删除时从列表中移除
      bookList.value = bookList.value.filter(b => b.id !== parseInt(bookId))
    }
  } else {
    // 如果是上架操作且书籍不在列表中，重新获取列表
    if (status === 1) {
      getBooks();
    }
  }
}

// 添加新书籍处理函数
const handleNewBookPublished = (bookData) => {
  // 将新书籍添加到列表开头
  bookList.value.unshift({
    ...bookData,
    likeCount: 0,
    rating: null,
    tags: Array.isArray(bookData.tags) 
      ? bookData.tags 
      : (bookData.tags ? bookData.tags.split(/\s+/).filter(tag => tag) : [])
  })
}

// 处理书籍更新
const handleBookUpdated = (bookData) => {
  // console.log('收到书籍更新通知:', bookData)
  // 查找并更新对应书籍
  const index = bookList.value.findIndex(book => book.id === parseInt(bookData.id))
  if (index !== -1) {
    // 更新书籍信息，保留原来的点赞数和评分等统计数据
    const originalBook = bookList.value[index]
    bookList.value[index] = {
      ...originalBook, // 保留原来的属性
      title: bookData.title,
      author: bookData.author,
      thoughts: bookData.thoughts,
      tags: Array.isArray(bookData.tags) 
        ? bookData.tags 
        : (bookData.tags ? bookData.tags.split(/\s+/).filter(tag => tag) : []),
      images: bookData.images,
      reading_url: bookData.reading_url,
      status: parseInt(bookData.status)
    }
    
    // 如果状态变为下架，则从列表中移除
    if (bookData.status === 0) {
      bookList.value = bookList.value.filter(book => book.id !== parseInt(bookData.id))
    }
  }
}

onMounted(() => {
  getBooks()
  // 连接 WebSocket
  wsClient.connect()
  // 监听书籍状态变化
  wsClient.on('book_status_change', handleBookStatusChange)
  // 监听新书籍发布消息
  wsClient.on('new_book_published', handleNewBookPublished)
  // 监听书籍更新消息
  wsClient.on('book_updated', handleBookUpdated)
})

onUnmounted(() => {
  // 移除监听器，提供相同的函数引用
  wsClient.off('book_status_change', handleBookStatusChange)
  wsClient.off('new_book_published', handleNewBookPublished)
  wsClient.off('book_updated', handleBookUpdated)
})
</script>

<style scoped>
.home {
  padding: 20px;
  background-color: #ffffff;
  min-height: 100vh;
}

.book-col {
  margin-bottom: 30px;
}

/* 书籍卡片样式 */
.book-card {
  height: 100%;
  cursor: pointer;
  transition: all 0.3s;
  overflow: hidden;
  border-radius: 12px;
  border: 1px solid #dcdfe6;
  background-color: #f9f9fb;
}

.book-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

/* 书籍封面图片样式 */
.book-cover {
  width: 100%;
  height: 200px;
  position: relative;
  overflow: hidden;
  border-radius: 8px;
  background-color: #f5f7fa;
}

.book-image {
  width: 100%;
  height: 100%;
}

/* 图片占位符样式 */
.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  color: #909399;
}

.image-placeholder .el-icon {
  font-size: 24px;
}

/* 书籍信息区域样式 */
.book-info {
  padding: 10px 0;
}

.book-title {
  margin: 10px 0 5px;
  font-size: 16px;
  font-weight: bold;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.book-author {
  color: #666;
  font-size: 14px;
  margin-bottom: 8px;
}

.book-sharer {
  color: #666;
  font-size: 13px;
  margin-bottom: 8px;
}

.book-description {
  color: #666;
  font-size: 14px;
  margin-bottom: 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 书籍元数据样式（标签和统计） */
.book-meta {
  margin-bottom: 10px;
}

.tags {
  margin-bottom: 8px;
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

.stats {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 12px;
}

.like-count {
  font-size: 14px;
  color: #909399;
}

.rating {
  display: flex;
  align-items: center;
  gap: 4px;
}

.rating-label {
  color: #666;
  font-size: 14px;
}

.rating-value {
  font-size: 14px;
  color: #ff9900;
  font-weight: bold;
}

.rating-value.no-rating {
  color: #909399;
  font-weight: normal;
}

/* 卡片底部样式 */
.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid #eee;
  padding-top: 10px;
  margin-top: 10px;
}

.create-time {
  color: #909399;
  font-size: 12px;
}

/* Element Plus 卡片组件样式覆盖 */
:deep(.el-card) {
  border: 1px solid #dcdfe6;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
  border-radius: 12px;
  background-color: #f9f9fb;
}
</style>
